package LogThread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class LogWriter {
	public void writeLog(String msg_buf, String log_path) {
		
		
		File w_file = null;
		String filename = null;
		BufferedReader buffRead = null;
		BufferedWriter buffWrite = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		
		Calendar cal = Calendar.getInstance();
		Date currentTime = cal.getTime();
		String date = sdf.format(currentTime);
		
		String fileContent = "";
		int b = -1;
		
		if (log_path.length() == 0) {
			System.out.println("WriteLog Fail");
			return;
		}
		
		try {
			filename = log_path + (date + ".txt");
			w_file = new File(filename);
			
			if(w_file.exists()){
				System.out.println("로그파일 업데이트 : "+filename);
			}else{
				w_file.createNewFile();
				System.out.println("로그파일 생성 : "+filename);
			}
			
			buffRead = new BufferedReader(new FileReader(w_file));
			while ((b = buffRead.read()) != -1) {
				fileContent += (char) b;
			}
			buffRead.close();
			
			buffWrite = new BufferedWriter(new FileWriter(w_file));
			String write_str = fileContent + msg_buf;
			
			buffWrite.write(write_str, 0, write_str.length());
			buffWrite.flush();
			
			Memory.mmr_log = "";
			
		} catch (IOException e) {
			System.out.println("Error " + e.toString());
			e.printStackTrace();
			System.exit(-2);
		} finally {
			try {
				buffWrite.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
